﻿using HandyControl.Interactivity;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace Enterprises.Wpf.Sample.Behavior
{
    public class CustomTextBindingBehavior : Behavior<FrameworkElement>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            SetBinding();
        }

        private void SetBinding()
        {
            if (AssociatedObject != null)
            {
                // 创建一个新的 Binding 对象  
                //Binding binding = new Binding("Postion")
                //{
                //    // 设置其他 Binding 属性，如 Mode, Converter 等  
                //    Mode = BindingMode.TwoWay,
                //    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                //    // ... 其他你需要的设置  
                //};

                var bindingExpression = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
                if (bindingExpression != null)
                {
                    // 你可以访问BindingExpression的一些属性，如ParentBinding, Status等  
                    var binding = bindingExpression.ParentBinding;
                    Binding newBinding = new Binding();
                    newBinding.Path = binding.Path;
                    if (binding.Source != null)
                    {
                        newBinding.Source= binding.Source;
                    }

                    newBinding.Mode = binding.Mode;
                    newBinding.UpdateSourceTrigger = binding.UpdateSourceTrigger;

                    BindingOperations.SetBinding(AssociatedObject, TextBox.TextProperty, newBinding);
                }

                // 将 Binding 应用到 TextBox 的 Text 属性上  
                //BindingOperations.SetBinding(AssociatedObject, TextBox.TextProperty, binding);
            }
        }

        // 其他行为逻辑...  
    }
}
